import { Tooltip, List, Card, Modal } from 'antd';
import { useEffect, useState } from 'react';
import { Comment } from '@ant-design/compatible';
import '@/assets/css/comment.css';
import CommentActions from './CommentActions';
import TextArea from 'antd/es/input/TextArea';
import { useAddComment } from '@/services/comment';
import { useModel } from '@umijs/max';
import dayjs from 'dayjs';
import { useDeleteLike, useUpdateLike } from '@/services/like';

type NestCommentProps = {
  item: CommentType;
  children?: React.ReactNode;
};

const NestComment: React.FC<NestCommentProps> = ({ item, children }) => {
  return (
    <Comment
      actions={item.actions}
      author={item.author}
      avatar={item.avatar}
      content={item.content}
      datetime={item.datetime}
    >
      {children}
    </Comment>
  );
};

type CommentListProps = {
  data: CommentType[];
};

const CommentList: React.FC<CommentListProps> = ({ data }) => {
  const { initialState } = useModel('@@initialState');
  const [modalTitle, setModalTitle] = useState<string>('');
  const [modalContent, setModalContent] = useState<string>('');
  const [replyComment, setReplyComment] = useState<CommentType>({
    content: '',
    level: 0,
    datetime: '',
  });
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const { mutateAsync: addComment } = useAddComment();
  const { mutateAsync: deleteLike } = useDeleteLike();
  const { mutateAsync: updateLike } = useUpdateLike();

  const openModal = (comment: CommentType) => {
    setModalTitle(`你 回复 ${comment.author}`);
    setIsModalOpen(true);
    setReplyComment(comment);
  };
  const confirmModal = () => {
    addComment({
      accountId: initialState?.id,
      articleId: replyComment?.articleId ?? -1,
      parentId:
        replyComment?.level === 0 ? replyComment?.id : replyComment?.parentId,
      datetime: dayjs().format('YYYY-MM-DD hh:mm:ss'),
      content: modalContent,
      level: replyComment?.level === 0 ? 1 : 2,
      replyId: replyComment?.id,
    });
    setIsModalOpen(false);
  };

  const changeLike = (comment: CommentType, type: TLikes) => {
    if (
      (comment.status === 0 && type === 'like') ||
      (comment.status === 1 && type === 'dislike')
    )
      deleteLike({ accountId: initialState?.id, commentId: comment.id });
    else {
      let obj: API.ILike = {
        commentId: comment.id,
        accountId: initialState?.id,
        status: type === 'like' ? 0 : 1,
      };
      if (comment.lid) obj.id = comment.lid;
      updateLike(obj);
    }
  };

  // 转换数据
  const initData = (arr: CommentType[]): CommentType[] => {
    return arr.map((x) => {
      return {
        actions: [
          <CommentActions
            comment={x}
            key={x.id}
            onComment={(e) => openModal(e)}
            onLike={(c, s) => changeLike(c, s)}
          ></CommentActions>,
        ],
        author: x.nickName + (x?.level === 2 ? ' 回复 ' + x.replyNickName : ''),
        avatar: x.avatar,
        level: x.level,
        content: <p>{x.content}</p>,
        datetime: (
          <Tooltip>
            <span>{x.datetime}</span>
          </Tooltip>
        ),
        children:
          x.children && x.children.length > 0 ? initData(x.children) : [],
      };
    });
  };

  const [commentList, setCommentList] = useState<CommentType[]>([]);

  useEffect(() => {
    setCommentList(initData(data));
  }, [data]);

  return (
    <>
      <List
        className="comment-list"
        header={`${commentList.length} 条评论`}
        itemLayout="horizontal"
        dataSource={commentList}
        style={{ textAlign: 'left' }}
        renderItem={(item) => (
          <li>
            <Card>
              <NestComment item={item}>
                {item?.children &&
                  item?.children?.map((x, i) => (
                    <NestComment key={i} item={x}></NestComment>
                  ))}
              </NestComment>
            </Card>
          </li>
        )}
      />
      <Modal
        title={modalTitle}
        open={isModalOpen}
        onOk={confirmModal}
        onCancel={() => setIsModalOpen(false)}
      >
        <TextArea
          value={modalContent}
          onChange={(e) => setModalContent(e.target.value)}
        ></TextArea>
      </Modal>
    </>
  );
};

export default CommentList;
